package rsj.monitor;

import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.helpers.TidHelper;
import com.rlyy.aibase.view.code.CacheCode_Enum;
import com.rlyy.aibase.view.code.DbCode_Enum;
import com.rlyy.aibase.view.key.APIKey_Enum;
import com.rlyy.aibase.view.key.ExceptKey_Enum;
import com.rlyy.aibase.view.key.STATUSKey_Enum;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.api.user.BaseLink;
import rsj.db.PostgresqlConn;
import rsj.utils.RedisUtils;

import java.sql.Connection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author          xuguoliang@rlyy.com
 * @date            2019/12/27 9:21
 * @description     系统运行监控接口
 * @package         rsj.monitor.MonitorInfoCheck
 */
@RestController
public class MonitorInfoCheck extends BaseLink {


    @RequestMapping(value = "rsj_monitor_health_check")
    public Box executeLink(Box in){

        StringBuffer prefix = null;
        StringBuffer suffix = null;
        if (in==null)in=new Box();
        in.putNode(APIKey_Enum.TID.getKey(), TidHelper.tid());
        try {
            //1.校验redis信息
//            String tid = TidHelper.tid();
//            String uid = UUID.randomUUID().toString().replace("-", "");
//            Box result = JedisUtil.getValues("rsj-" + uid, tid);
//            Map boxMap = JSONObject.parseObject(result.toJson(), Map.class);
//            if(boxMap.containsKey("$code") && null != boxMap.get("$code")) {
//                // 初始化对象
//                prefix = new StringBuffer();
//                suffix = new StringBuffer();
//                in.setCode(boxMap.get("$code")+"");
//                String ipaddress = boxMap.get(APIKey_Enum.NET.getKey()).toString().replace(".*(\\d{3}(\\.\\d{1,3}){3}).*", "$1");
//
//                // 拼接信息
//                prefix.append("redis").append(" ");
//                suffix.append("redis:").append(ipaddress).append(" ");
//            }
            String rsj = RedisUtils.getString("rsj");
        } catch (Exception e) {
            e.printStackTrace();
            prefix = new StringBuffer();
            suffix = new StringBuffer();
            in.setCode(CacheCode_Enum.TIMEOUT.getKey());
            // 拼接信息
            prefix.append("redis").append(" ");
        }

        try{
            //2.校验数据库连接信息
            Connection connection = PostgresqlConn.getConnectionMonitor();
            if(connection == null) {// 连接失败
                if(prefix == null || suffix == null){
                    // 初始化对象
                    prefix = new StringBuffer();
                    suffix = new StringBuffer();
                }
                in.setCode(DbCode_Enum.REFUSE.getKey());
                String ipaddress = getParamsUri(PostgresqlConn.getConnectionUriMonitor());
                prefix.append("pgsql");
                suffix.append("pgsql:").append(ipaddress);
            }
        } catch(Exception e){
            e.printStackTrace();
        }

        if(prefix != null || suffix != null) { // 有异常
            String prefixStr = prefix.append(":").toString().replaceAll(" ",",");
            String suffixStr = "[" + suffix.append("]").toString().replace(" ", ",");
            String msg = prefixStr + suffixStr;
            in.setMsg(msg);
            in.putNode(APIKey_Enum.STATUS.getKey(), STATUSKey_Enum.ERROR.getValue());

            MapNode mapNode = new MapNode();
            mapNode.putNode(ExceptKey_Enum.EXCEPT_CODE.getKey(),in.toMap().get("$code")+"");
            mapNode.putNode(ExceptKey_Enum.EXCEPT_MSG.getKey(),"系统异常，redis 或 pgsql连接异常");
            mapNode.putNode(ExceptKey_Enum.EXCEPT_LOG.getKey(),msg);
            in.putMapNode(APIKey_Enum.EXCEPT.getKey(),mapNode);

        } else { // 无异常
            in.putNode(APIKey_Enum.STATUS.getKey(), STATUSKey_Enum.OK.getValue());
        }
        return in;
    }


    public static String getParamsUri(String contiansUri){
        //  String ipaddress = PostgresqlConn.getConnectionUriMonitor().replace(".*(\\d{3}(\\.\\d{1,3}){3}).*", "$1");
        String returnUrl = null;
        String regexString="\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
        Pattern p = Pattern.compile(regexString);
        String parentString=contiansUri;
        Matcher m = p.matcher(parentString);
        boolean result = m.find();
        while(result) {
            returnUrl = m.group();
            result = m.find();
        }
        return returnUrl;
    }

    public static void main(String[] args) {

        Box out = new Box();
        MapNode mapNode = new MapNode();
        mapNode.putNode(ExceptKey_Enum.EXCEPT_CODE.getKey(),"");
        mapNode.putNode(ExceptKey_Enum.EXCEPT_MSG.getKey(),"");
        mapNode.putNode(ExceptKey_Enum.EXCEPT_LOG.getKey(),"");
        out.putMapNode(APIKey_Enum.EXCEPT.getKey(),mapNode);


        System.out.println("------------------------- 开始 --------------------------");
        System.err.println(out.toMap());
        System.out.println("------------------------- 结束 --------------------------");


    }


}
